# controllers/user_controller.py
from flask import render_template, request, redirect, url_for, flash
from models.database import SessionLocal
from models.user import User
from controllers.user_auth import requires_role, hash_password
from datetime import datetime

class UserController:
    def __init__(self, app):
        self.app = app
        self.register_routes()
    
    def register_routes(self):
        """注册路由"""
        self.app.route('/users')(self.users)
        self.app.route('/add-user', methods=['GET', 'POST'])(self.add_user)
        self.app.route('/edit-user/<int:user_id>', methods=['GET', 'POST'])(self.edit_user)
        self.app.route('/deactivate-user/<int:user_id>')(self.deactivate_user)
        self.app.route('/activate-user/<int:user_id>')(self.activate_user)
    
    @requires_role("root")
    def users(self):
        db = SessionLocal()
        try:
            users = db.query(User).order_by(User.id).all()
            return render_template('users.html', users=users)
        finally:
            db.close()
    
    @requires_role("root")
    def add_user(self):
        if request.method == 'POST':
            username = request.form['username']
            email = request.form.get('email')
            password = request.form['password']
            role = request.form['role']
            country = request.form.get('country') if role == 'user' else None
            
            # 禁止创建root权限用户
            if role == "root":
                return render_template('add_user.html', error='不允许创建超级管理员(root)用户', current_user=request.current_user)
            
            db = SessionLocal()
            try:
                # 检查用户名是否已存在
                existing_user = db.query(User).filter(User.username == username).first()
                if existing_user:
                    return render_template('add_user.html', error='用户名已存在', current_user=request.current_user)
                
                # 创建新用户
                import datetime as dt
                new_user = User(
                    username=username,
                    email=email,
                    password_hash=hash_password(password),
                    role=role,
                    country=country,
                    is_active=True,
                    created_at=dt.datetime.now(dt.UTC)
                )
                
                db.add(new_user)
                db.commit()
                return redirect(url_for('users'))
            except Exception as e:
                db.rollback()
                return render_template('add_user.html', error=f'创建用户时出错: {str(e)}', current_user=request.current_user)
            finally:
                db.close()
        
        return render_template('add_user.html', current_user=request.current_user)
    
    @requires_role("root")
    def edit_user(self, user_id):
        db = SessionLocal()
        try:
            user = db.query(User).filter(User.id == user_id).first()
            if not user:
                return "用户未找到", 404
            
            if request.method == 'POST':
                email = request.form.get('email')
                role = request.form['role']
                country = request.form.get('country') if role == 'user' else None
                is_active = request.form.get('is_active') == 'on'
                
                # 禁止将用户修改为root权限
                if role == "root":
                    return render_template('edit_user.html', user=user, current_user=request.current_user, error='不允许将用户修改为超级管理员(root)权限')
                
                # 更新用户信息
                user.email = email
                user.role = role
                user.country = country
                user.is_active = is_active
                
                # 如果提供了新密码，则更新密码
                new_password = request.form.get('password')
                if new_password:
                    user.password_hash = hash_password(new_password)
                
                db.commit()
                return redirect(url_for('users'))
            
            return render_template('edit_user.html', user=user, current_user=request.current_user)
        finally:
            db.close()
    
    @requires_role("root")
    def deactivate_user(self, user_id):
        db = SessionLocal()
        try:
            user = db.query(User).filter(User.id == user_id).first()
            if user:
                user.is_active = False
                db.commit()
            return redirect(url_for('users'))
        finally:
            db.close()
    
    @requires_role("root")
    def activate_user(self, user_id):
        db = SessionLocal()
        try:
            user = db.query(User).filter(User.id == user_id).first()
            if user:
                user.is_active = True
                db.commit()
            return redirect(url_for('users'))
        finally:
            db.close()